package com.studerb.nntp;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.commons.net.SocketFactory;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.studerb.service.interfaces.ISettingsService;

public class TimeoutSocketFactory implements SocketFactory {
    @Autowired private ISettingsService settingsService;
    private Logger log = Logger.getLogger(NntpConnection.class);
    private int timeoutInMs;

    public TimeoutSocketFactory() {
    }

    public ServerSocket createServerSocket(int port) throws IOException {
        throw new RuntimeException("createSocket(int) is not supported");
    }

    public ServerSocket createServerSocket(int port, int backlog) throws IOException {
        throw new RuntimeException("createSocket(int, int) is not supported");
    }

    public ServerSocket createServerSocket(int port, int backlog, InetAddress bindAddress) throws IOException {
        throw new RuntimeException("createSocket(int, int, InetAddress) is not supported");
    }

    public Socket createSocket(InetAddress hostAddress, int port) throws IOException {
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress(hostAddress, port), timeoutInMs);
        return socket;
    }

    public Socket createSocket(InetAddress remoteAddress, int remotePort, InetAddress localAddress, int localPort)
                    throws IOException {
        throw new RuntimeException("createSocket(InetAddress, int, InetAddress, int) is not supported");
    }

    public Socket createSocket(String hostname, int port) throws IOException {
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress(hostname, port), timeoutInMs);
        return socket;
    }

    public Socket createSocket(String remoteHost, int remotePort, InetAddress localAddress, int localPort)
                    throws IOException {
        throw new RuntimeException("createSocket(String, int, InetAddress, int) is not supported");
    }

    public void init() {
        String timeout = settingsService.getSetting("TimeoutSocketFactory.timeout");
        timeoutInMs = Integer.parseInt(timeout);
        log.debug("setting connection timeout to: " + timeoutInMs);
    }
}